<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #pagination>
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <!-- 账单生成时间 -->
            <el-form-item prop="timeBetween">
              <el-date-picker
                :placeholder="$t('时间选择')"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')"
                @change="getList"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                v-model="queryParams.timeBetween"
                type="datetimerange"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 账单类型 -->
            <el-form-item prop="type">
              <el-select :placeholder="$t('账单类型')" clearable v-model="queryParams.type" @change="handleQuery">
                <el-option
                  v-for="item in bill_type_distributor_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="skuNo">
              <el-input :placeholder="$t('sku编号')" v-model="queryParams.skuNo" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <div style="font-size: 15px; margin-right: 10px">
          供应商余额:
          <span style="font-weight: bold" v-hasPermi="['distribution:fundsDistributor:query']">
            {{ capitalPool ? (+capitalPool).toFixed() : '' }}
          </span>
        </div>
        <el-button
          type="primary"
          v-hasPermi="['distribution:billDistributor:export']"
          @click="handleExport"
          plain
          size="mini"
        >
          时间范围导出
        </el-button>
        <el-button
          v-hasPermi="['distribution:billDistributorWithdraw:list']"
          size="mini"
          @click="handleWithdrawalRecord"
        >
          {{ $t('提现记录') }}
        </el-button>
        <el-tooltip
          effect="dark"
          content="收入在30天后会变成可结算状态，每月10号会对所有可结算账单进行汇款结算"
          placement="top-start"
        >
          <el-button size="mini" type="text" icon="el-icon-info" circle></el-button>
        </el-tooltip>
      </template>
    </PageSearch>

    <el-table :height="calTableHeight() - 50" v-loading="loading" ref="TableRef" :data="tableData" row-key="menuId">
      <el-table-column align="center" show-overflow-tooltip width="150" prop="afterFunds" :label="$t('业务类型')">
        <template slot-scope="{ row }">
          <span :style="{ color: $randomColor(row.type) }"> {{ handleType(row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="payAmount" :label="$t('金额')">
        <template slot-scope="{ row }">
          <div>{{ row.payAmount ? (+row.payAmount).toFixed() : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="afterFunds" :label="$t('变动类型(增加/减少)')">
        <template slot-scope="{ row }">
          <span :style="{ color: $randomColor(row.changeType) }" v-if="row.changeType == 1">增加</span>
          <span :style="{ color: $randomColor(row.changeType) }" v-if="row.changeType == 2">减少</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="beforeFunds" :label="$t('变化前金额')">
        <template slot-scope="{ row }">
          <div>{{ row.beforeFunds ? (+row.beforeFunds).toFixed() : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="afterFunds" :label="$t('变化后金额')">
        <template slot-scope="{ row }">
          <div>{{ row.afterFunds ? (+row.afterFunds).toFixed() : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="isWithdraw" :label="$t('能否结算')">
        <template slot-scope="{ row }">
          <span v-if="row.paid == 1">是</span>
          <span v-if="row.paid == 0">否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="" :label="$t('是否生成提现单')">
        <template slot-scope="{ row }">
          <span v-if="row.isWithdraw == 1">是</span>
          <span v-if="row.isWithdraw == 0">否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="createTime" :label="$t('创建时间')" />
      <el-table-column align="center" show-overflow-tooltip prop="" :label="$t('操作')">
        <template slot-scope="{ row }">
          <el-button
            v-hasPermi="['distribution:billDistributor:query']"
            v-show="row.type !== 14"
            type="text"
            size="mini"
            @click="handleDetail(row)"
          >
            查询业务详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pageTotal > 0"
      :total="pageTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <WithdrawalRecord
      :show.sync="WithdrawalRecord.show"
      :title="WithdrawalRecord.title"
      :data="WithdrawalRecord.data"
    />
    <Detail
      :FormData="FormData"
      :type="detailInfo.type"
      :show.sync="detailInfo.show"
      :title="detailInfo.title"
      :data="detailInfo.data"
    />
  </div>
</template>

<script>
import Detail from './components/detail.vue'
import { list, balance, billDistributor } from '@/api/bill/distributerBalance'
import { useDict } from '@/utils/useDict'
import WithdrawalRecord from './components/WithdrawalRecord.vue'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'distributerBalance',
  components: {
    WithdrawalRecord,
    Detail,
  },
  data() {
    return {
      FormData: {},
      /**详情信息 */
      detailInfo: {
        /**显示详情 */
        show: false,
        type: '',
        title: '',
        data: [],
        query: {},
      },
      capitalPool: '0',
      showSearch: false,
      /**提现记录 */
      WithdrawalRecord: {
        /**显示详情 */
        show: false,
        type: '',
        title: '提现记录',
        data: [],
        query: {},
      },

      /**
       * 账单类型
       */
      bill_type_distributor_list: [],
      tableData: [],
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        timeBetween: [],
        pageNum: 1,
        pageSize: 10,
        type: '',
      },
    }
  },
  created() {
    this.getList()
    useDict('bill_type_distributor').then(({ bill_type_distributor }) => {
      this.bill_type_distributor_list = bill_type_distributor
    })
  },
  mounted() {
    this.getbalance()
  },
  methods: {
    handlePayType(type) {
      const index = this.bill_type_distributor_list.findIndex((i) => i.dictValue == type)
      if (index > -1) return this.bill_type_distributor_list[index].dictLabel
    },
    handleDetail(row) {
      const { id, type } = row
      billDistributor(id).then((res) => {
        const { code, data } = res
        this.FormData = data
        if (code === 200) {
          this.detailInfo.show = true
          this.detailInfo.title = this.handlePayType(type)
          this.detailInfo.type = type
          this.detailInfo.data = []
          switch (type) {
            case 1 /**.	1.订单批次sku费用 type=1 */:
              this.detailInfo.data = data.orderBatchSkuFeeData
              break
            case 4 /** type=4 */:
              this.detailInfo.data = [data.reissueSkuFeeData]
              break
            case 5 /** type=5 */:
              this.detailInfo.data = data.returnSkuFeeToSeller
              break
            case 8 /** type=8 */:
              this.detailInfo.data = data.profitStockCheckData
              break
            case 9 /** type=9 */:
              this.detailInfo.data = data.lossStockCheckData
              break
            case 10 /** type=10 */:
              this.detailInfo.data = [data.reissueSkuFeeUnderTake]
              break
            case 13 /** type=13 */:
              this.detailInfo.data = [data.billDistributorWithdrawVo]
              break
            case 15 /** type=15 */:
              this.detailInfo.data = [data.returnSkuFreightBaleFeeToSeller]
              break
            case 16 /** type=16 */:
              this.detailInfo.data = [data.reissueSkuFreightBaleFeeUnderTake]
              break
            case 17 /** type=17 */:
              this.detailInfo.data = [data.platformCompensateData]
              break
            case 18 /** type=18 取消订单*/:
              this.detailInfo.data = data.cancelOrderPackageSkuList
              break
            case 19 /** type=19 买家拒收退还sku费用*/:
              this.detailInfo.data = []
              break
            default:
              break
          }
        }
      })
    },
    /**获取对应字段 */
    handleType(type) {
      const index = this.bill_type_distributor_list.findIndex((i) => i.dictValue == type)
      return this.bill_type_distributor_list[index]?.dictLabel
    },
    /**获取供应商资金池 */
    getbalance() {
      balance().then((res) => {
        this.capitalPool = res.data
      })
    },
    /**时间范围导出 */
    handleExport() {
      if (!this.queryParams.timeBetween || this.queryParams.timeBetween.length == 0) {
        return this.$message({ type: 'error', message: this.$t('请选择时间范围') })
      }
      const data = {
        ...this.queryParams,

        startTime: this.queryParams.timeBetween[0],
        endTime: this.queryParams.timeBetween[1],
      }
      delete data.timeBetween
      this.download(
        '/distribution/billDistributor/export',
        {
          ...data,
        },
        `platformBalance_${new Date().getTime()}.xlsx`,
      )
    },
    handleWithdrawalRecord(type = '') {
      this.WithdrawalRecord.show = true
      // this.WithdrawalRecord.type = type
    },

    /** 查询菜单列表 */
    getList() {
      this.loading = true
      const params = JSON.parse(JSON.stringify(this.queryParams))
      const { timeBetween } = params
      const startTime = timeBetween ? timeBetween[0] : ''
      const endTime = timeBetween ? timeBetween[1] : ''
      delete params.timeBetween
      const data = {
        ...params,
        startTime,
        endTime,
      }
      list(data).then((res) => {
        this.tableData = res.rows
        this.pageTotal = res.total
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.keys(this.queryParams).forEach((key) => (this.queryParams[key] = ''))
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
  },
}
</script>
<style lang="scss"></style>
